package com.flx.dis.read.write.split.config;

import com.flx.dis.read.write.split.enums.DBTypeEnum;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: Fenglixiong
 * @Date: 2021/6/16 17:36
 * @Description: 切换数据源工具
 */
@Slf4j
public class DBContextHolder {

    private static final ThreadLocal<DBTypeEnum> contextHolder = new ThreadLocal<>();
    private static final AtomicInteger counter = new AtomicInteger(-1);

    /**
     * 切换数据源
     */
    public static void set(DBTypeEnum dbType) {
        contextHolder.set(dbType);
    }

    /**
     * 获取数据源
     */
    public static DBTypeEnum get() {
        return contextHolder.get();
    }

    /**
     * 重置数据源
     */
    public static void clear() {
        contextHolder.remove();
    }

    /**
     * 切换数据源
     */
    public static void master() {
        log.info("切换到master！");
        contextHolder.set(DBTypeEnum.MASTER);
    }

    /**
     * 切换数据源
     */
    public static void slave() {
        //  轮询
        int index = counter.getAndIncrement() % 2;
        if (counter.get() > 9999) {
            counter.set(-1);
        }
        if (index == 0) {
            set(DBTypeEnum.SLAVE1);
            System.out.println("切换到slave1");
        }else {
            set(DBTypeEnum.SLAVE2);
            System.out.println("切换到slave2");
        }
    }


}
